package mobile

import (
	"encoding/xml"
	"fmt"
	"strings"
)

// Envelope  定义 XML 结构体
type Envelope struct {
	XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
	Body    Body     `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
}

// Body  定义 XML 结构体
type Body struct {
	Invoke Invoke `xml:"http://SCService.chinatelecom.com invoke"`
}

// Invoke  定义 XML 结构体
type Invoke struct {
	XMLData string `xml:"xmlData"`
}

// ParseReqXMLData 从 SOAP 消息中提取 xmlData 内容
func ParseReqXMLData(soapMessage string) (string, error) {

	var env Envelope
	err := xml.Unmarshal([]byte(soapMessage), &env)
	if err != nil {
		return "", fmt.Errorf("解析 XML 出错: %v", err)
	}

	content := strings.TrimSpace(env.Body.Invoke.XMLData)
	return content, nil
}

// GenRespXMLData 生成返回的 SOAP 消息
func GenRespXMLData(content string) (string, error) {
	// 定义 SOAP 报文模板
	soapTemplate := `
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:scs="http://SCService.chinatelecom.com">
   <soapenv:Header/>
   <soapenv:Body>
      <scs:invokeResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
         <invokeReturn xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"><![CDATA[%s]]></invokeReturn>
      </scs:invokeResponse>
   </soapenv:Body>
</soapenv:Envelope>
	`
	// 格式化最终的 SOAP 报文
	return fmt.Sprintf(soapTemplate, content), nil
}
